package cn.itcast.mybatis.mapper;

import cn.itcast.mybatis.po.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

import java.io.InputStream;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2018/3/27.
 */
public class UserMapperTest {
    private SqlSessionFactory sqlSessionFactory =null;

    @Before
    public void  init () throws Exception {
        String resource = "SqlMapConfig.xml";

        //第二部加载配置文件
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //第三部创建sqlsessionFactory对象
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

    }
    @Test
    public void findUserById()  {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user = userMapper.findUserById(10);
        System.out.println(user);
        sqlSession.close();
    }

    @Test
    public void findUserByName()  {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        List<User> lsit = userMapper.findUserByName("张");
        for (User user : lsit) {
            System.out.println(user);
        }
        sqlSession.close();
    }

    @Test
    public void insertUser() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user = new User();
        user.setUsername("张三");
        user.setBirthday(new Date());
        user.setSex("1");
        user.setAddress("北京市");
        //通过mapper接口添加用户
        userMapper.insertUser(user);
        //提交
        sqlSession.commit();
        //关闭session
        sqlSession.close();
    }



}
